﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SAE.Common
{
    public class LogUtility
    {
        /// <summary>
        /// Create a new log file with log head
        /// </summary>
        /// <param name="strFile"></param>
        /// <param name="strFileHead"></param>
        public static void CreateNewFile(string strFile, string strFileHead)
        {
            if (!System.IO.File.Exists(strFile))
            {
                System.IO.FileStream fs = System.IO.File.Create(strFile);
                //write log head into log file
                if (strFileHead != null && strFileHead.Length > 0)
                {
                    byte[] fileInfo = new System.Text.UTF8Encoding(true).GetBytes(strFileHead);
                    fs.Write(fileInfo, 0, fileInfo.Length);
                }
                fs.Close();
            }
        }

        public static void AppendLog(string strFile, string strContent)
        {
            //If strFile exists , append log.
            if (System.IO.File.Exists(strFile))
            {
                //Set file attributes to normal for writing data.
                System.IO.File.SetAttributes(strFile, System.IO.FileAttributes.Normal);
                System.IO.FileStream fs;
                fs = System.IO.File.OpenWrite(strFile);
                //Append strContent into log file
                if (strContent != null && strContent.Length > 0)
                {
                    strContent = Environment.NewLine + "---------------------" + Environment.NewLine + "[" + DateTime.Now.ToString() + "]: " + strContent;
                    byte[] fileInfo = new System.Text.UTF8Encoding(true).GetBytes(strContent);
                    fs.Position = fs.Length;
                    fs.Write(fileInfo, 0, fileInfo.Length);
                }
                fs.Close();
            }
            else
            {
                //If strFile does not exist , create a new log.
                CreateNewFile(strFile, "Event Log");
                AppendLog(strFile, strContent);
            }
        }
    }
}
